<script setup>
  import { ref, onMounted } from 'vue'
  import { getNotifyListApi, readAllApi } from '@/apis/message.js'

  const notifyList = ref([])
  const nextPage = ref(1)
  const pageSize = ref(10)
  const isEmpty = ref(false)
  const hasMore = ref(true) // 控制是否加载更对数据

  // 1. 获取任务通知列表
  const getNotifyList = async (page = 1, pageSize = 10) => {
    // 1.1 调用接口
    const { code, data } = await getNotifyListApi(201, page, pageSize) // 201-司机端系统通知
    if (code !== 200) return uni.utils.toast('获取任务通知失败~')
    // notifyList.value = data.items || []

    // 1.6 判断是否是下拉刷新(拿第一页的数据)
    // 如果是下拉刷新, 则需要清空数据数组
    if (page === 1) notifyList.value = []

    // 1.3 让页码++
    nextPage.value = ++data.page

    // 1.4 合并数据
    notifyList.value = [...notifyList.value, ...(data.items || [])]

    // 1.2 判断是否为空
    isEmpty.value = data.items.length === 0

    // 1.5 判断是否有更多数据
    // data.pages 总页数   nextPage.value 下一页
    hasMore.value = nextPage.value <= data.pages
  }

  // 0. 第一次(加载第一页数据)
  onMounted(() => {
    getNotifyList()
  })

  // 2. 上拉加载更多
  const onScrollToLower = () => {
    // 2.1 判断是否有更多数据
    if (!hasMore.value) return uni.utils.toast('没有更多数据了...')
    // 2.2 加载下一页数据
    getNotifyList(nextPage.value)
  }

  // 3. 触发下拉刷新
  const isTriggered = ref(false)
  const onRefresh = async () => {
    // 开启下拉刷新交互
    isTriggered.value = true
    // 请求数据
    await getNotifyList()
    // 关闭下拉刷新交互
    isTriggered.value = false
  }

  // 4. 全部已读
  const onReadAll = async () => {
    await readAllApi(201)
    getNotifyList()
  }
</script>
<template>
  <scroll-view
    class="scroll-view"
    refresher-enabled
    scroll-y
    :refresher-triggered="isTriggered"
    @scrolltolower="onScrollToLower"
    @refresherrefresh="onRefresh"
  >
    <view class="scroll-view-wrapper">
      <view class="message-action" @click="onReadAll">
        <text class="iconfont icon-clear"></text>
        全部已读
      </view>
      <uni-card
        v-for="item in notifyList"
        :key="item.id"
        :border="false"
        :is-shadow="false"
      >
        <view class="brief">{{ item.content }}</view>
        <view class="extra">
          <text class="time">{{ item.created }}</text>
          <navigator
            hover-class="none"
            class="link"
            :url="`/subpkg_message/content/index?id=${item.id}`"
            >查看详情</navigator
          >
        </view>
        <template v-slot:title>
          <view class="title" :class="{ unread: item.isRead === 0 }">{{
            item.title
          }}</view>
        </template>
      </uni-card>
      <view v-if="isEmpty" class="message-blank">暂无消息</view>
    </view>
  </scroll-view>
</template>

<style lang="scss" scoped>
  @import './styles.scss';
</style>
